import Vue from 'vue'
import VueDraggableResizable from 'vue-draggable-resizable'
Vue.component('vue-draggable-resizable', VueDraggableResizable)

export default {
  methods: {
    initDrag(tbCols) {
      // 第一步：列宽映射
      const draggingMap = {}
      tbCols.forEach(col => {
        draggingMap[col.key] = col.width
      })
      const draggingState = Vue.observable(draggingMap)
      // 第二步：表头渲染
      return (h, props, children) => {
        // 表头DOM
        let thDom = null
        // 获取列的key值和特性
        const { key, ...restProps } = props
        // 获取当前列
        const col = tbCols.find(col => {
          const k = col.dataIndex || col.key
          return k === key
        })
        // 如果当前列没有设置宽度, 直接返回
        if (!col || (col && !col.width)) {
          return <th {...restProps}>{children}</th>
        }

        // 开始拖拽监听
        const onDrag = x => {
          draggingState[key] = 0
          col.width = Math.max(x, 1)
        }
        // 停止拖拽监听
        const onDragstop = () => {
          draggingState[key] = thDom.getBoundingClientRect().width
        }
        return (
          <th {...restProps} v-ant-ref={r => (thDom = r)} width={col.width} class="resize-table-th">
            {children}
            <vue-draggable-resizable
              key={col.key}
              class="table-draggable-handle"
              w={10}
              x={draggingState[key] || col.width}
              z={1}
              axis="x"
              draggable={true}
              resizable={false}
              onDragging={onDrag}
              onDragstop={onDragstop}
            ></vue-draggable-resizable>
          </th>
        )
      }
    }
  }
}


